package com.kj.xuyuan.http;

import com.kj.xuyuan.base.Constants;
import com.kj.xuyuan.util.LogUtils;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http.HttpHeaders;
import okio.Buffer;


public class LogInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        if(!request.method().equals("GET")){
            if(Constants.LOG_ENABLE) {
                StringBuilder builder = new StringBuilder("Request[");
                builder.append(request.url())
                        .append("]\nheader=[\n")
                        .append(request.headers())
                        .append("\n]body=[\n")
                        .append(isPlaintext(request.body().contentType()) ? bodyToString(request) : "body: maybe [file part] , too large too print , ignored!")
                        .append("\n]");
                LogUtils.e("TAG",builder.toString());
            }

        }

        if(!Constants.LOG_ENABLE)
        {
            return chain.proceed(request);
        }

        //执行请求，计算请求时间
        long startNs = System.nanoTime();
        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            LogUtils.e("TAG","["+request.url()+"]<-- HTTP FAILED: " + e);
            throw e;
        }
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

        return logForResponse(response,tookMs);
    }

    private Response logForResponse(Response response, long tookMs) {
        Response.Builder builder = response.newBuilder();
        Response clone = builder.build();
        ResponseBody responseBody = clone.body();
        boolean logBody = true;

        try {
            String strBody=null;
            boolean bInterceptBody = false;
            if (logBody && HttpHeaders.hasBody(clone)) {
                if (isPlaintext(responseBody.contentType())) {
                    bInterceptBody = true;
                    strBody = responseBody.string();
                } else {
                    strBody="body: maybe [file part] , too large too print , ignored!";
                }
            }

            StringBuilder strBuilder = new StringBuilder("Response[");
            strBuilder.append(clone.code()).append("][")
                    .append(clone.message())
                    .append("][")
                    .append(clone.request().url())
                    .append("][")
                    .append(tookMs)
                    .append("ms],header=[")
                    .append(clone.request().headers())
                    .append("]\n")
                    .append(strBody);
            LogUtils.e("TAG",strBuilder.toString());

            if(bInterceptBody)
            {
                responseBody = ResponseBody.create(responseBody.contentType(), strBody);
                return response.newBuilder().body(responseBody).build();
            }
        } catch (Exception e) {
            LogUtils.e("TAG",e.getMessage());
        }
        return response;
    }

    /**
     * Returns true if the body in question probably contains human readable text. Uses a small sample
     * of code points to detect unicode control characters commonly used in binary file signatures.
     */
    private static boolean isPlaintext(MediaType mediaType) {
        if (mediaType == null) return false;
        if (mediaType.type() != null && mediaType.type().equals("text")) {
            return true;
        }
        String subtype = mediaType.subtype();
        if (subtype != null) {
            subtype = subtype.toLowerCase();
            if (subtype.contains("x-www-form-urlencoded") ||
                    subtype.contains("json") ||
                    subtype.contains("xml") ||
                    subtype.contains("html")) //
                return true;
        }
        return false;
    }
    private String bodyToString(Request request) {
        try {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            Charset charset = UTF8;
            MediaType contentType = copy.body().contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            return buffer.readString(charset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
